#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@Time    :   2021/03/31 21:49:03
@Author  :   Leo Wood 
@Contact :   leowood@foxmail.com
@Disc    :   API调用示例
'''

import requests
import socket
import json
from tqdm import tqdm

 
api_question = {
        "ip":"localhost", # api_server的ip，若本机访问，则为localhost
        "port":8881, # api_server的port，与启动脚本保持一致
    }


api_def = {
        "ip":"localhost", # api_server的ip，若本机访问，则为localhost
        "port":8882, # api_server的port，与启动脚本保持一致
    }


api_citation = {
        "ip":"localhost", # api_server的ip，若本机访问，则为localhost
        "port":8882, # api_server的port，与启动脚本保持一致
    }


def predict_ques_def_citation(text):

    results_return = {'question':[],'definition':[],'citation':[]}
    # 预测问题句：
    api = api_question
    url = 'http://' + api["ip"] + ":" + str(api["port"]) + '/Cla_Result'
    data = {'text': text}
    response = requests.post(url,data=data)
    result = response.text
    try:
        sens = json.loads(result)['gold_sens']
        results_return['question'] += sens
    except:
        print(result)
        exit()
    
    # 预测定义句：
    api = api_def
    url = 'http://' + api["ip"] + ":" + str(api["port"]) + '/Cla_Result'
    data = {'text': text}
    response = requests.post(url,data=data)
    result = response.text
    try:
        sens = json.loads(result)['gold_sens']
        results_return['definition'] += sens
    except:
        print(result)
        exit()
    
    # 预测引用句
    api = api_citation
    url = 'http://' + api["ip"] + ":" + str(api["port"]) + '/Cla_Result'
    data = {'text': text}
    response = requests.post(url,data=data)
    result = response.text
    try:
        sens = json.loads(result)['gold_sens']
        results_return['citation'] += sens
    except:
        print(result)
        exit()

    print(results_return)
    return results_return
    
    
        

# def predict_with_api_get(text): ## GET方式调用示例
#     ### 检测能否成功访问api_server
#     sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#     sk.settimeout(1)
#     flag = 0
#     try:
#         sk.connect((api["ip"], api["port"]))
#         flag = 1
#     except:
#         pass
#     sk.close()

#     if not flag:
#         print('api server 无法访问')
#         return 0

#     ### 传入文本，获取模型预测标签和预测分值
#     url = 'http://' + api["ip"] + ":" + str(api["port"]) + '/Cla_Result'

#     params = {'text': text}

#     response = requests.get(url,params=params)
    
#     result = response.content

#     return result


# def predict_with_api_post(text): ## POST方式调用示例
#     ### 检测能否成功访问api_server
#     sk = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
#     sk.settimeout(1)
#     flag = 0
#     try:
#         sk.connect((api["ip"], api["port"]))
#         flag = 1
#     except:
#         pass
#     sk.close()

#     if not flag:
#         print('api server 无法访问')
#         return 0

#     ### 传入文本，获取模型预测标签和预测分值
#     url = 'http://' + api["ip"] + ":" + str(api["port"]) + '/Cla_Result'

#     data = {'text': text}

#     response = requests.post(url,data=data)
    
#     result = response.text

#     return result



if __name__ == "__main__":
    # text = "Arrhythmogenic right ventricular dysplasia (ARVD) was first recognized in 1977 during antiarrhythmic surgery in Pitié Salpêtrière Hospital, Paris, France [1]. The dysplasia predominantly involved the original “triangle of dysplasia” (Fig.1). The diagnosis of ARVD was pathologically based on previous findings of myocardium embedded in or bordered by fatty tissue and/or fibrosis (Fig.2) [1–4]. Biventricular involvement (Fig.3) is very frequently observed at later stages, leading to congestive heart failure and death [5–10]. Naxos disease is a special form of ARVD, which was first described by Dr. Nikos Protonotarios and colleagues on the island of Naxos, Greece [11] and then in other regions [12–21]. It is an inherited condition with a recessive form of transmission and a familial penetrance of 90% [11, 22–27]. It is associated with thickening of the skin of the hands and sole, and a propensity to woolly hair. The cardiac anomalies characterized by ventricular arrhythmias with ventricular extrasystoles and tachycardia and histologic features of the myocardium are consistent with ARVD, but in a more severe form of dysplasia with major dilatation of the right ventricle [23, 25, 26, 28–30]. The identification of the responsible first gene on chromosome 17, and its product plakoglobin as the responsible protein for Naxos disease proved to be a milestone in the study of ARVD, which opened a new field of research [28, 31]. In this review, we provide an impressive historical overview of events and developments that lead to the appearance of the Naxos disease concept in the context of ARVD. The review provides a first-hand account and bears a great deal of personal touch in description of the important historical events."
    # result = predict_ques_def_citation(text)
    # print(result)

    count = 0
    data_path = '/data/leo/Projects/UER-py/work/PubMed_Pretrain_Process/pubmed_oa_paras_100_new.txt'
    with open(data_path,'r') as f:
        for line in tqdm(f.readlines()):
            text = line.strip()
            print
            if text:
                try:
                    predict_ques_def_citation(text)
                    count += 1
                except Exception as e:
                    print(text)
                    print(e)
                
    print(count)

